﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PeerToPeer
{
    public partial class FrmServer : Form
    {
        public FrmServer()
        {
            InitializeComponent();
        }

        private void btn_Start_Click(object sender, EventArgs e)
        {
            Task.Run(new Action(() => { Start(); })); 
        }
        private void Start()
        {
            TcpListener tcpListener = new TcpListener(IPAddress.Any, 3721);            
            tcpListener.Start();
            PushMsg($"启动侦听！\r\n");
            while (true)
            {
                TcpClient client1 = tcpListener.AcceptTcpClient();
                var remoteEndPoint1 = client1.Client.RemoteEndPoint.ToString();
                PushMsg($"{remoteEndPoint1}连接上我了！\r\n");
                TcpClient client2 = tcpListener.AcceptTcpClient();
                var remoteEndPoint2 = client2.Client.RemoteEndPoint.ToString();
                PushMsg($"{remoteEndPoint2}连接上我了！\r\n");
                var bytes = Encoding.UTF8.GetBytes(remoteEndPoint2);
                var stream1 = client1.GetStream();
                stream1.Write(bytes, 0, bytes.Length);
                stream1.Flush();
                stream1.Close();
                client1.Close();
                PushMsg($"{remoteEndPoint2}转发出去了！\r\n");
                bytes = Encoding.UTF8.GetBytes(remoteEndPoint1);
                var stream3 = client2.GetStream();
                stream3.Write(bytes, 0, bytes.Length);
                stream3.Flush();
                stream3.Close();
                client2.Close();
                PushMsg($"{remoteEndPoint1}转发出去了！\r\n");
                PushMsg($"继续等待下一轮！---------\r\n");
            }
        }
        private void PushMsg(string Msg)
        {
            this.BeginInvoke(new Action(() =>
            {
                rtb_Msg.AppendText(Msg);
            }));
        }

        private void rtb_Msg_TextChanged(object sender, EventArgs e)
        {

        }
    }
}
